import { setStorage, getStorage } from '@/utils/storage'

interface useAuthCodeOptions {
  seconds?: number
  startText?: string
  changeText?: `x${string}`
  endText?: string
  keepRunning?: boolean
  uniqueKey?: string
  timer: () => void
}
export function useAuthCode(options: useAuthCodeOptions) {
  //配置
  const seconds = options.seconds ?? 60
  const endText = options.endText ?? '重新获取'
  const changeText = options.changeText ?? 'x秒查询获取'
  const uniqueKey = options.uniqueKey
    ? 'authCode'
    : options.uniqueKey + 'authCode'
  const keepRunning = options.keepRunning !== false
  let noInterval = false
  const clock = ref<number>(initClock())
  const codeText = ref<string>(
    options.startText ? options.startText : '获取验证码'
  )
  //定时器
  const timer = ref()
  //禁止点击
  const disabled = computed(() => {
    return seconds !== clock.value
  })

  keepRunning && disabled.value && countDown(true)
  function countDown(initFlag = false) {
    console.log((!initFlag && disabled.value) || (initFlag && !disabled.value))
    if ((!initFlag && disabled.value) || (initFlag && !disabled.value)) return
    if (!initFlag) {
      setStorage(uniqueKey, new Date().getTime() + seconds * 1000)
    }

    if (!noInterval) {
      timer.value = setInterval(intervalHandle(), 1000)
    } else {
      codeText.value = changeText.replace('x', clock.value + ' ')
      --clock.value
      setTimeout(() => {
        noInterval = false
        reset()
      }, 1000)
    }
  }

  function intervalHandle() {
    --clock.value
    codeText.value = changeText.replace('x', clock.value + ' ')
    if (clock.value <= 0) reset()
    return intervalHandle
  }
  function initClock() {
    let clockValue = seconds
    if (keepRunning && getStorage(uniqueKey)) {
      const now = new Date().getTime()
      const diffDate = getStorage(uniqueKey) - now
      if (parseInt(diffDate / 1000) > 0) {
        clockValue = parseInt(diffDate / 1000)
        if (clockValue == 1) {
          noInterval = true
        }
      } else setStorage(uniqueKey, '')
    }
    return clockValue
  }
  function reset() {
    clearInterval(timer.value)
    clock.value = seconds
    codeText.value = endText
    options?.timer()
    setStorage(uniqueKey, '')
  }
  return {
    codeText,
    countDown,
    disabled,
    clock
  }
}
